<style lang="less">
.upload-image .el-upload--picture-card {
  background: transparent;
  .el-icon-plus {
    color: #fff;
  }
}
</style>
<template>
  <div class="comp-new">
    <el-form ref="newForm" :model="newForm" :label-width="150 + 'px'">
      <el-form-item
        label="设备名称："
        prop="name"
        :rules="[{ required: true, message: '请输入设备名称' }]"
      >
        <el-input placeholder="请输入" v-model.trim="newForm.name"></el-input>
      </el-form-item>
      <el-form-item
        label="设备编号："
        prop="number"
        :rules="[{ required: true, message: '请输入设备编号' }]"
      >
        <el-input placeholder="请输入" v-model.trim="newForm.number"></el-input>
      </el-form-item>
      <el-form-item label="物联网卡号：">
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.internetofthingsCardnum"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="!isChildren"
        label="传输装置编码："
        prop="transDeviceCode"
        :rules="[{ required: type == 19, message: '请输入传输装置编码' }]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.transDeviceCode"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="设备类型："
        prop="deviceType"
        :rules="[{ required: true, message: '请选择设备类型' }]"
      >
        <el-select
          class="full"
          v-model="newForm.deviceType"
          placeholder="请选择"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, key) in typeList"
            :key="key"
            :disabled="item.id == '1001' && isChildren == 1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="newForm.deviceType == '30'" label="计量单位：">
        <el-input
          placeholder="请输入计量单位"
          v-model="newForm.unit"
          style="width: 158px"
        ></el-input>
      </el-form-item>
      <template v-if="type == 8">
        <el-form-item
          label="宽度："
          prop="ledWidth"
          :rules="[
            { required: true, message: '请输入宽度' },
            { type: 'number', message: '宽度须为数字' },
          ]"
        >
          <el-input
            placeholder="请输入"
            v-model.trim.number="newForm.ledWidth"
            style="width: 100px"
          ></el-input>
          px
        </el-form-item>
        <el-form-item
          label="高度："
          prop="ledHeight"
          :rules="[
            { required: true, message: '请输入高度' },
            { type: 'number', message: '高度须为数字' },
          ]"
        >
          <el-input
            placeholder="请输入"
            v-model.trim.number="newForm.ledHeight"
            style="width: 100px"
          ></el-input>
          px
        </el-form-item>
        <el-form-item
          label="音量："
          prop="ledVolume"
          :rules="[{ type: 'number', message: '音量须为数字' }]"
        >
          <el-slider
            v-model="newForm.ledVolume"
            :min="0"
            :max="100"
          ></el-slider>
          <!-- <el-input placeholder="请输入" v-model.trim.number="newForm.volume"></el-input> -->
        </el-form-item>
        <el-form-item
          label="文字大小："
          prop="ledFontSize"
          :rules="[
            { required: true, message: '请输入文字大小' },
            { type: 'number', message: '文字大小须为数字' },
          ]"
        >
          <el-input
            placeholder="请输入"
            v-model.trim.number="newForm.ledFontSize"
            style="width: 100px"
          ></el-input>
          px
        </el-form-item>
      </template>

      <el-form-item
        label="安装时间："
        prop="installtime"
        :rules="[{ required: true, message: '请选择安装时间' }]"
      >
        <el-date-picker
          v-model="newForm.installtime"
          placeholder="请选择"
          type="date"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="安装位置："
        prop="position"
        :rules="[{ required: true, message: '请输入安装位置' }]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.position"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="经纬度："
        prop="lon"
        :rules="[{ required: true, message: '请选择经纬度' }]"
      >
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input
              readonly
              placeholder="经纬度"
              type="text"
              :value="coord"
            ></el-input>
          </div>
          <div>
            <el-button type="green" @click="locateAction">定位</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="设备图片：">
        <el-upload
          class="upload-image"
          :action="config.uploadUrl"
          :data="{ token: siteInfos.token }"
          list-type="picture-card"
          :file-list="fileList"
          accept="image/*"
          :on-success="handleUploadSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :disabled="!$store.getters.hasEditPermission"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="产品："
        prop="productId"
        :rules="[{ required: true, message: '请选择产品' }]"
      >
        <el-select
          class="full"
          v-model="newForm.productId"
          placeholder="请选择"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, key) in productList"
            :key="key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分组：" v-if="type == 18">
        <el-select
          class="full"
          v-model="newForm.ultrasonicGroupId"
          placeholder="请选择"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, key) in groupList"
            :key="key"
          ></el-option>
        </el-select>
        <!-- <el-input placeholder="请" v-model.trim="newForm.spec"></el-input> -->
      </el-form-item>
      <el-form-item label="规格：" v-else>
        <el-input
          placeholder="请输入设备规格(设备长*宽*高)"
          v-model.trim="newForm.spec"
        ></el-input>
      </el-form-item>
      <el-form-item label="报警电话：">
        <el-input
          placeholder="请输入报警电话"
          v-model.trim="newForm.alarmPhone"
        ></el-input>
        <!-- （多个电话请使用英文逗号隔开） -->
      </el-form-item>
      <el-form-item
        label="安装人员："
        prop="installperson"
        :rules="[{ required: false, message: '请输入安装人员' }]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.installperson"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="安装人员电话："
        prop="installpersonPhone"
        :rules="[{ required: false, message: '请输入安装人员电话' }]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.installpersonPhone"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注：">
        <el-input
          placeholder="请输入"
          type="text"
          v-model.trim="newForm.remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 定位 start -->
    <el-dialog
      v-if="locationModalVisible"
      :visible.sync="locationModalVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <h2 slot="title" class="fs-18">定位 <small>（点击地图选点）</small></h2>
      <Location
        ref="location"
        :coord="coord"
        :area="unit.areaName"
        type="equipment"
        @save="saveLocation"
        @cancel="locationModalVisible = false"
      >
      </Location>
    </el-dialog>
    <!-- 定位 end -->
    <el-dialog
      :visible.sync="previewVisible"
      v-if="previewVisible"
      append-to-body
    >
      <img style="max-width: 100%" :src="previewImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import Location from "@/components/census/record/Location.vue";
export default {
  name: "newEquipment",
  components: {
    Location,
  },
  props: {
    activeData: {
      type: Object,
      default() {
        return null;
      },
    },
    unit: {
      type: Object,
      default() {
        return {};
      },
    },
    type: {
      type: String,
      default: "",
    },
    isChildren: {
      type: Number,
    },
  },
  computed: {
    ...mapState(["siteInfos"]),
    coord() {
      if (this.newForm.lon) {
        return this.newForm.lon + "," + this.newForm.lat;
      }
    },
  },
  watch: {
    activeData() {
      this.initForm();
    },
    fileList(fileList) {
      let urls = fileList.map((item) => item.url);
      this.newForm.img = urls.join(",");
    },
  },
  data() {
    return {
      newForm: {},
      loading: false,
      typeList: [],
      productList: [],
      locationModalVisible: false,
      fileList: [],
      previewImageUrl: "",
      previewVisible: false,
      groupList: [],
    };
  },
  created() {
    console.log(this.isChildren);
    this.getType();
    this.getProduct();
    this.initForm();
    if (this.type == 18) {
      this.getGroup();
    }
  },
  methods: {
    getGroup() {
      const businessId =
        this.siteInfos.userType == 1 ? this.unit.id : this.siteInfos.homeId;
      this.$get("/fireFightingIOT/ultrasonic/groupList", { businessId }).then(
        (res) => {
          this.groupList = res.data;
        }
      );
    },
    initForm() {
      if (this.activeData) {
        this.newForm = this.utils.pick(this.activeData, [
          "id",
          "businessId",
          "businessName",
          "deviceClassify",
          "img",
          "lon",
          "lat",
          "name",
          "number",
          "position",
          "internetofthingsCardnum",
          "transDeviceCode",
          "deviceType",
          "installtime",
          "productId",
          "spec",
          "alarmPhone",
          "installperson",
          "installpersonPhone",
          "remark",
          "isChildren",
          "unit",
        ]);
        if (this.type == 8) {
          this.$set(this.newForm, "ledWidth", +this.activeData.ledWidth);
          this.$set(this.newForm, "ledHeight", +this.activeData.ledHeight);
          this.$set(this.newForm, "ledFontSize", +this.activeData.ledFontSize);
          this.$set(this.newForm, "ledVolume", +this.activeData.ledVolume);
        } else if (this.type == 18) {
          this.$set(
            this.newForm,
            "ultrasonicGroupId",
            +this.activeData.ultrasonicGroupId
          );
        }
        let imgList = this.activeData.imgList.map((item, index) => {
          return {
            name: "file" + index,
            url: item,
          };
        });
        this.fileList = imgList;
      } else {
        const businessId =
          this.siteInfos.userType == 1 ? this.unit.id : this.siteInfos.homeId;
        const businessName =
          this.siteInfos.userType == 1
            ? this.unit.name
            : this.siteInfos.homeName;

        this.newForm = {
          businessId,
          businessName,
          deviceClassify: this.type,
          img: "",
          lon: "",
          lat: "",
          isChildren: this.isChildren,
        };
        if (this.$refs["newForm"]) {
          this.$refs["newForm"].resetFields();
        }
      }
    },
    getType() {
      this.$get("/fireFightingIOT/device/deviceTypeList", {
        type: this.type,
      }).then(
        (res) => {
          this.typeList = res.data;
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getProduct() {
      this.$get("/fireFightingIOT/device/productList", {
        type: this.type,
      }).then(
        (res) => {
          this.productList = res.data;
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    locateAction() {
      this.locationModalVisible = true;
    },
    saveLocation(coord) {
      this.newForm.lon = coord[0];
      this.newForm.lat = coord[1];
      this.locationModalVisible = false;
    },
    handlePictureCardPreview(file) {
      this.previewImageUrl = file.url;
      this.previewVisible = true;
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({ name: res.data.fileName, url: res.data.filePath });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList.map((item) => {
        return { name: item.name, url: item.url };
      });
    },
    submitAction() {
      this.newForm.transDeviceCode =
        this.newForm.transDeviceCode == undefined
          ? this.unit.number
          : this.newForm.transDeviceCode;

      let params = Object.assign({ deviceClassify: this.type }, this.newForm);
      if (this.isChildren !== 1) {
        delete this.newForm.isChildren;
      }
      if (this.isChildren == 1 && !params.id) {
        params.number = this.unit.number + this.newForm.number;
      }
      console.log(params, "param");
      this.$refs["newForm"].validate((valid) => {
        if (valid) {
          this.$emit("submitting");
          this.loading = true;
          let url = !params.id
            ? "/fireFightingIOT/device/typeAdd"
            : "/fireFightingIOT/device/typeUpdate";
          this.$ajax({
            url: url,
            method: "post",
            data: params,
          }).then(
            (data) => {
              this.loading = false;
              this.$message.success("保存成功");
              this.$emit("success", data);
            },
            (error) => {
              this.loading = false;
              this.$message.error(error.msg);
              this.$emit("fail");
            }
          );
        } else {
          return false;
        }
      });
    },
    cancelAction() {
      this.$emit("cancel");
    },
    // resetForm () {
    // 	this.newForm = {}
    // 	this.$refs['newForm'].resetFields()
    // }
  },
};
</script>
